#include "RangedWeaponsManager.h"
#include "RangedWeapons.h"
#include "../mainScreen/CommonDefinition.h"
#include "EnemyBase.h"

RangedWeaponsManager *RangedWeaponsManager::m_pRangedWeaponsManager = NULL;

RangedWeaponsManager::RangedWeaponsManager()
	:m_iCurToRemoveIndex(0)
	, m_iRangedWeaponsCollisionBaseMask(RANGEDWEAPONS_BASE_MASK)
{
}

RangedWeaponsManager::~RangedWeaponsManager()
{
}

bool RangedWeaponsManager::init()
{
	if (cocos2d::Node::init())
	{
		scheduleUpdate();
		return true;
	}

	return false;
}

RangedWeapons *RangedWeaponsManager::searchCollisioRangedWeapons(const cocos2d::PhysicsBody* pRangedWeaponsPhysicsBody)
{
	RangedWeapons *pTemp = NULL;
	for (auto &rangedWeapon : m_setRangedWeapons)
	{
		if (pRangedWeaponsPhysicsBody == rangedWeapon->getRangedWeaponsPhysicsBody())
		{
			pTemp = rangedWeapon;
			break;
		}
	}
	return pTemp;
}

void RangedWeaponsManager::removeRangedWeapons(RangedWeapons *pCollisionRangedWeapons)
{
	pCollisionRangedWeapons->setAlive(false);
	m_setToRemoveRangedWeapons[m_iCurToRemoveIndex].insert(pCollisionRangedWeapons);
	m_setRangedWeapons.erase(pCollisionRangedWeapons);
}

void RangedWeaponsManager::createEnemy(EnemyBase *pSrcEnemy, const cocos2d::Sprite *pTargetSprite, const cocos2d::Vec2 heroPos)
{
	RangedWeapons *pRangedWeapons = NULL;
	
	pRangedWeapons = RangedWeapons::create(pSrcEnemy, pTargetSprite, heroPos);

	if (pRangedWeapons)
	{
		m_pRangedWeaponsManager->addChild(pRangedWeapons, 8);
		m_setRangedWeapons.insert(pRangedWeapons);

		pRangedWeapons->setInteractionBitmask(m_iRangedWeaponsCollisionBaseMask << (m_setRangedWeapons.size() - 1));
	}
}

void RangedWeaponsManager::update(float delta)
{
	cocos2d::Node::update(delta);
	m_iCurToRemoveIndex = (m_iCurToRemoveIndex + 1) % 2;
	for (auto &rangedWeapon : m_setToRemoveRangedWeapons[m_iCurToRemoveIndex])
	{
		rangedWeapon->removeFromParent();
	}
	m_setToRemoveRangedWeapons[m_iCurToRemoveIndex].clear();
}

void RangedWeaponsManager::onExit()
{
	cocos2d::Node::onExit();
	unscheduleUpdate();
}

RangedWeaponsManager* RangedWeaponsManager::getInstance()
{
	if (NULL == m_pRangedWeaponsManager){
		m_pRangedWeaponsManager = create();
	}

	return m_pRangedWeaponsManager;
}